package com.example.sherlockzhong.plush_v2.Models;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;

import com.example.sherlockzhong.plush_v2.Constant;
import com.example.sherlockzhong.plush_v2.Utils.DateTimeUtil;
import com.example.sherlockzhong.plush_v2.Utils.HashmapJsonUtil;
import com.example.sherlockzhong.plush_v2.Utils.StorageUtils;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.File;
import java.util.HashMap;

/**
 * Created by SherlockZhong on 9/18/14.
 */
public class DataModel {

    public static JSONArray cardData;

    public static boolean sync() {
        PushModel.listSubscribedPosters();
        return ClassesModel.updateClass();
    }

    public static JSONArray refresh() {
        try {
            JSONArray dataToUpdate = new JSONArray();
            JSONObject dataToSave = new JSONObject();

            boolean changedFlag = false;

            long weekNumber = DateTimeUtil.getWeekNumberOfSchoolYear();
            String currentDate = DateTimeUtil.getCurrentTime("yyyy-MM-dd");

            JSONObject status = getStatus();
            String dataUpdateDate = (status == null) ? "" : status.getString("data_update_date");

            // 获取天气
            try {
                String weatherDueTime = DateTimeUtil.getCurrentTime("yyyy-MM-dd") + " 08:00";
                if (!currentDate.equalsIgnoreCase(dataUpdateDate) && DateTimeUtil.timeIsPast(weatherDueTime)) {
                    HashMap weatherHashMap = WeatherModel.getWeatherHashMap();
                    String weatherJson = "";
                    if (weatherHashMap != null) {
                        weatherJson = HashmapJsonUtil.hashmapToJson(weatherHashMap);
                    }
                    JSONTokener jsonTokener = new JSONTokener(weatherJson);
                    JSONObject weather = (JSONObject) jsonTokener.nextValue();
                    weather.put("card_type", "weather");
                    dataToUpdate.put(weather);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            // 获取课程卡片
            if (weekNumber > 0 && weekNumber < 20) {
                String currentClass = (status == null || !status.has("current_class")) ? "" : status.getString("current_class");
                JSONObject classToUpdate = getClassToUpdate();
                if (classToUpdate != null && (!classToUpdate.getString("class_name").equalsIgnoreCase(currentClass) || !currentDate.equalsIgnoreCase(dataUpdateDate))) {
                    dataToUpdate.put(classToUpdate);
                    dataToSave.put("current_class", classToUpdate.getString("class_name"));
                } else {
                    dataToSave.put("current_class", currentClass);
                }
            }

            // 获取社团消息
            JSONArray news = PushModel.getSubscribedNews();
            if (news != null && news.length() > 0) {
                for (int i = 0; i < news.length(); i++) {
                    JSONObject oneNews = (JSONObject) news.get(i);
                    if (oneNews.getString("type").equalsIgnoreCase("1")) {
                        oneNews.put("card_type", "organization");
                    } else if (oneNews.getString("type").equalsIgnoreCase("2")) {
                        oneNews.put("card_type", "myclass");
                    } else if (oneNews.getString("type").equalsIgnoreCase("3")) {
                        oneNews.put("card_type", "tutor");
                    } else if (oneNews.getString("type").equalsIgnoreCase("4")) {
                        oneNews.put("card_type", "official");
                    }
                    dataToUpdate.put(oneNews);
                }
            }

            // 获取todo
            JSONArray todoList = getTodoToUpdate();
            if (todoList != null && todoList.length() > 0) {
                for (int i = 0; i < todoList.length(); i++) {
                    JSONObject todoItem = todoList.getJSONObject(i);
                    todoItem.put("card_type", "todo");
                    dataToUpdate.put(todoItem);
                }
            }

            // 获取校园卡消费信息
            JSONArray ecardRecords = EcardModel.getData("refresh");
            if (ecardRecords != null && ecardRecords.length() > 0) {
                for (int i = 0; i < ecardRecords.length(); i++) {
                    JSONObject ecardRecord = (JSONObject) ecardRecords.get(i);
                    ecardRecord.put("card_type", "ecard");
                    dataToUpdate.put(ecardRecord);
                }
            }

            dataToSave.put("data_update_date", currentDate);
            StorageUtils.saveAsFile("Status.json", dataToSave.toString());

            return dataToUpdate;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public static boolean saveHistoryData(JSONArray data) {
        cardData = data;
        if (data.length() > 50) {
            try {
                JSONArray newData = new JSONArray();
                for (int i = data.length() - 50; i < data.length(); i++) {
                    newData.put(data.get(i));
                }
                data = newData;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return StorageUtils.saveAsFile("HistoryData.json", data.toString());
    }

    public static JSONArray retrieveHistoryData() {
        String raw = StorageUtils.retrieveFromFile("HistoryData.json");
        try {
            JSONTokener jsonTokener = new JSONTokener(raw);
            return (JSONArray) jsonTokener.nextValue();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static boolean saveCollectedData(JSONArray data) {
        return StorageUtils.saveAsFile("CollectedData.json", data.toString());
    }

    public static JSONArray retrieveCollectedData() {
        try {
            String raw = StorageUtils.retrieveFromFile("CollectedData.json");
            if (raw != null) {
                JSONTokener jsonTokener = new JSONTokener(raw);
                return (JSONArray) jsonTokener.nextValue();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void removeUserData(Activity activity) {
        Constant.STUDENT_ID = null;
        Constant.STUDENT_TOKEN = null;
        Constant.ECARD_VERIFIED = false;
        SharedPreferences sp = activity.getSharedPreferences("user", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.remove("token");
        editor.remove("ecardVerified");
        editor.remove("count");
        editor.commit();
        StorageUtils.removeDirectory(new File(StorageUtils.baseDir.toString()));
    }

    private static JSONObject getStatus() {
        if (StorageUtils.fileExists("/data/Status.json")) {
            try {
                JSONTokener jsonTokener = new JSONTokener(StorageUtils.retrieveFromFile("Status.json"));
                return (JSONObject) jsonTokener.nextValue();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    private static JSONObject getClassToUpdate() {
        long setTimeGap = (long) Constant.CLASS_WARNING_TIME;
        int weekdayIndex = DateTimeUtil.getWeekdayIndex();
        long weekNumber = DateTimeUtil.getWeekNumberOfSchoolYear();
        String weekNumberString = (weekNumber < 10) ? "0" + weekNumber : "" + weekNumber;
        String currentTimeString = DateTimeUtil.getCurrentTime("HH:mm");
        JSONArray classesOfDay = ClassesModel.findByDay(weekdayIndex);
        if (classesOfDay == null) {
            return null;
        }
        try {
            for (int i = 0; i < classesOfDay.length(); i++) {
                JSONObject oneClass = (JSONObject) classesOfDay.get(i);
                if (!oneClass.getString("class_name").equalsIgnoreCase("empty")) {
                    String oneClassStartTime = DateTimeUtil.getClassStartTime(oneClass.getString("class_order"));
                    if (oneClass.getString("weeks").contains(weekNumberString) && DateTimeUtil.getTimeGap(currentTimeString, oneClassStartTime) < setTimeGap) {
                        oneClass.put("card_type", "class");
                        return oneClass;
                    }
                    if (oneClass.has("sub_class")) {
                        JSONTokener jsonTokener = new JSONTokener(oneClass.getString("sub_class"));
                        JSONObject subClass = (JSONObject) jsonTokener.nextValue();
                        String subClassStartTime = DateTimeUtil.getClassStartTime(subClass.getString("class_order"));
                        if (subClass.getString("weeks").contains(weekNumberString) && DateTimeUtil.getTimeGap(currentTimeString, subClassStartTime) < setTimeGap) {
                            subClass.put("card_type", "class");
                            return subClass;
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    private static JSONArray getTodoToUpdate() {
        try {
            String currentDateTime = DateTimeUtil.getCurrentTime("yyyy-MM-dd HH:mm");
            String currentDate = currentDateTime.split(" ")[0];
            String currentTime = currentDateTime.split(" ")[1];
            JSONArray oldTodoList = TodoModel.retrieveTodoList();
            if (oldTodoList == null || oldTodoList.length() <= 0) {
                return null;
            }
            JSONArray newTodoList = new JSONArray();
            JSONArray result = new JSONArray();
            for (int i = 0; i < oldTodoList.length(); i++) {
                JSONObject todoItem = oldTodoList.getJSONObject(i);
                String todoDueDateTime = todoItem.getString("due_time");
                String todoDueDate = todoDueDateTime.split(" ")[0];
                String todoDueTime = todoDueDateTime.split(" ")[1];
                if ((todoDueDate.equalsIgnoreCase(currentDate) && DateTimeUtil.getTimeGap(todoDueTime, currentTime) <= 5) || DateTimeUtil.timeIsPast(todoDueDateTime)) {
                    result.put(todoItem);
                } else {
                    newTodoList.put(todoItem);
                }
            }
            StorageUtils.saveAsFile("TodoList.json", newTodoList.toString());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
